package com.si.control.action;

import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Random;

public class FourLayCollageAction extends CollageAction {

	private final Random random;

	public FourLayCollageAction() {
		this.random = new Random();
	}

	@Override
	protected BufferedImage doCollage(final List<BufferedImage> argument) throws Exception {
		final BufferedImage result = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_RGB);
		this.overlay(result, argument, 0, this.width/2, 0, this.height/2);
		this.overlay(result, argument, this.width/2, this.width, 0, this.height/2);
		this.overlay(result, argument, 0, this.width/2, this.height/2, this.height);
		this.overlay(result, argument, this.width/2, this.width, this.height/2, this.height);
		return result;
	}


	private void overlay(final BufferedImage target, final List<BufferedImage> source, final int xstart, final int xend,
			final int ystart, final int yend) {
		final int length = source.size();
		final BufferedImage img1 = source.get(this.randomIndex(length));
		BufferedImage img2 = source.get(this.randomIndex(length));
		while(img2 == img1) img2 = source.get(this.randomIndex(length));
		int xi = xstart;
		for(int x = xstart; x < xend; x++) {
			int yi = ystart;
			for(int y = ystart; y < yend; y++) {
				int rgb = 0;
				if(this.select()) {
					if(xi >= img1.getWidth()) xi = 0;
					if(yi >= img1.getHeight()) yi = 0;
					rgb = img1.getRGB(xi, yi);
				} else {
					if(xi >= img2.getWidth()) xi = 0;
					if(yi >= img2.getHeight()) yi = 0;
					rgb = img2.getRGB(xi, yi);
				}
				yi++;
				target.setRGB(x, y, rgb);
			}
			xi++;
		}
	}

	private int randomIndex(final int length) {
		return this.random.nextInt() & (length-1);
	}
	
	private boolean select() {
		final double d = this.random.nextDouble();
		if(d < 0.5) return true;
		return false;
	}
}
